//
//  AddShopViewController.m
//  GetPowerDBO
//
//  Created by 周博 on 2017/6/14.
//  Copyright © 2017年 BogoZhou. All rights reserved.
//

#import "AddShopViewController.h"

#import "AddShopTableViewCell1.h"
#import "AddShopTableViewCell2.h"
#import "AddShopTableViewCell3.h"
#import "AddShopTableViewCell4.h"
#import "AddShopTableViewCell5.h"
#import "AddShopTableViewCell6.h"

#define kCell1 @"AddShopTableViewCell1"
#define kCell2 @"AddShopTableViewCell2"
#define kCell3 @"AddShopTableViewCell3"
#define kCell4 @"AddShopTableViewCell4"
#define kCell5 @"AddShopTableViewCell5"
#define kCell6 @"AddShopTableViewCell6"


@interface AddShopViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSString *_shopName;
    NSString *_merPerson;
    NSString *_merPsersonNum;
    NSString *_shopPlaceDetail;
    NSString *_remark;
    
    NSString *_pName;
    NSString *_cName;
    NSString *_aName;
    NSString *_pId;
    NSString *_cId;
    NSString *_aId;
    
    NSString *_position;
    NSString *_position_name;
    
    NSString *_from_type;
    
    NSString *_latitude;
    NSString *_longitude;
    
    NSString *_imageUrl;
}
@property (nonatomic,strong) NSArray *dataArray;
@property (nonatomic,strong) NSArray *upDateArray;
@end

@implementation AddShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self UISetting];
    [self getNoti];
    NSString *jumpTyp = [[NSUserDefaults standardUserDefaults] valueForKey:@"jumpType"];
    if (jumpTyp.integerValue == 1) {
        [self settingInfo];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
}

- (void)UISetting{
    NSLog(@"array -> %@",self.dataArray);
    _upDateArray = [NSArray array];
}

- (void)settingInfo{
    UIButton *button;
    UITextField  *textField;
    BGTextView *bgTextView;
    
    NSString *shopType;          //场所
    NSString *dianPuLaiYuan;   //店铺来源
    NSString *city;                   //省市
    NSString *shopPlace;          //地理位置
    UIImage *shopImage;                //商家图片
    
    textField = [self.view viewWithTag:501];
    textField.text = _model.name;
    _shopName = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    button = [self.view viewWithTag:502];
    button.titleLabel.text = _model.position_name;
    _position_name = _model.position_name;
    _position = _model.position;
    shopType = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    button = [self.view viewWithTag:503];
    button.titleLabel.text = _model.from_type.integerValue == 1? @"自谈" : @"第三方合作";
    _from_type = _model.from_type;
    dianPuLaiYuan = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    textField = [self.view viewWithTag:504];
    textField.text = _model.contact;
    _merPerson = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    textField = [self.view viewWithTag:505];
    textField.text = _model.tel;
    _merPsersonNum = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    button = [self.view viewWithTag:506];
    button.titleLabel.text = [NSString stringWithFormat:@"%@-%@-%@",_model.province_name,_model.city_name,_model.area_name];
    _pName = _model.province_name;
    _pId = _model.province_id;
    _cName = _model.city_name;
    _cId = _model.city_id;
    _aName = _model.area_name;
    _aId = _model.area_id;
    city = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    button = [self.view viewWithTag:507];
    button.titleLabel.text = [NSString stringWithFormat:@"%@,%@",_model.latitude,_model.longitude];
    _latitude = _model.latitude;
    _longitude = _model.longitude;
    shopPlace = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    textField = [self.view viewWithTag:508];
    textField.text = _model.specific_address;
    _shopPlaceDetail = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    bgTextView = [self.view viewWithTag:509];
    bgTextView.text = [BGFunctionHelper isNULLOfString:_model.remark] ? @"" : _model.remark;
    _remark = [BGFunctionHelper isNULLOfString:bgTextView.text] ? @"" : bgTextView.text;
    
    button = [self.view viewWithTag:510];

    UIImageView *imageView = [[UIImageView alloc] init];
    _imageUrl = _model.img_url;
    [imageView sd_setImageWithURL:[NSURL URLWithString:_model.img_url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [button setBackgroundImage:imageView.image forState:UIControlStateNormal];
    }];
    
    _upDateArray = @[@""
                     ,_model.name
                     ,_model.position_name
                     ,_model.from_type.integerValue == 1? @"自谈" : @"第三方合作"
                     ,_model.contact
                     ,_model.tel
                     ,[NSString stringWithFormat:@"%@-%@-%@",_pName,_cName,_aName]
                     ,[NSString stringWithFormat:@"%@,%@",_latitude,_longitude]
                     ,_model.specific_address
                     ,[BGFunctionHelper isNULLOfString:_model.remark] ? @"" : _model.remark
                     ,_imageUrl];
    [_tableView reloadData];
}

- (void)getNoti{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(placeSettingByNoti:) name:@"place" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(cellSaveFunc) name:@"cellSaveButtonClick" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getImageUrl:) name:@"imgUrl" object:nil];
}

- (void)getImageUrl:(NSNotification *)noti{
    _imageUrl = noti.object;
}

- (void)cellSaveFunc{
    UIButton *button;
    UITextField  *textField;
    BGTextView *bgTextView;
    
    NSString *shopType;          //场所
    NSString *dianPuLaiYuan;   //店铺来源
    NSString *city;                   //省市
    NSString *shopPlace;          //地理位置
    UIImage *shopImage;                //商家图片
    
    textField = [self.view viewWithTag:501];
    _shopName = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    button = [self.view viewWithTag:502];
    shopType = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    button = [self.view viewWithTag:503];
    dianPuLaiYuan = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    textField = [self.view viewWithTag:504];
    _merPerson = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    textField = [self.view viewWithTag:505];
    _merPsersonNum = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    button = [self.view viewWithTag:506];
    city = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    button = [self.view viewWithTag:507];
    shopPlace = [BGFunctionHelper isNULLOfString:button.titleLabel.text] ? @"" : button.titleLabel.text;
    
    textField = [self.view viewWithTag:508];
    _shopPlaceDetail = [BGFunctionHelper isNULLOfString:textField.text] ? @"" : textField.text;
    
    bgTextView = [self.view viewWithTag:509];
    _remark = [BGFunctionHelper isNULLOfString:bgTextView.text] ? @"" : bgTextView.text;
    
    button = [self.view viewWithTag:510];
    shopImage = button.currentBackgroundImage;

    if ([BGFunctionHelper isNULLOfString:_shopName]) {
        [self alertVCByTitle:@"请输入店铺名称"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:shopType]) {
        [self alertVCByTitle:@"请选择所在场所"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:dianPuLaiYuan]) {
        [self alertVCByTitle:@"请选择店铺来源"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:_merPerson]) {
        [self alertVCByTitle:@"请输入联系人"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:_merPsersonNum]) {
        [self alertVCByTitle:@"请输入联系人电话"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:city]) {
        [self alertVCByTitle:@"请选择店铺所在城市"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:shopPlace]) {
        [self alertVCByTitle:@"请对店铺进行定位"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:_shopPlaceDetail]) {
        [self alertVCByTitle:@"请输入店铺详细地址"];
        return;
    }
    if ([BGFunctionHelper isNULLOfString:_imageUrl]) {
        [self alertVCByTitle:@"请选择店铺图片"];
        return;
    }
    
    NSString *jumpTyp = [[NSUserDefaults standardUserDefaults] valueForKey:@"jumpType"];
    
    if (jumpTyp.integerValue == 1) {
        [self updateData];
    }else if (jumpTyp.integerValue == 2){
        //上传文件信息
        [self uploadData];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"cellSaveButtonClick" object:nil];
}

- (void)placeSettingByNoti:(NSNotification *)noti{
    NSDictionary *dic = noti.object;
    
    NSIndexPath *indexPath = dic[@"indexPath"];
    
    UIButton *button = [self.view viewWithTag:500 + indexPath.row];
    [button setTitle:dic[@"name"] forState:UIControlStateNormal];
    
    if (indexPath.row == 6) {
        NSArray *nameArray = [dic[@"name"] componentsSeparatedByString:@"-"];
        if (nameArray.count == 3) {
            _pName = nameArray[0];
            _cName = nameArray[1];
            _aName = nameArray[2];
            [[NSUserDefaults standardUserDefaults] setValue:_pName forKey:@"pName"];
            [[NSUserDefaults standardUserDefaults] setValue:_cName forKey:@"cName"];
            [[NSUserDefaults standardUserDefaults] setValue:_aName forKey:@"aName"];

        }
        NSArray *idArray = [dic[@"id"] componentsSeparatedByString:@"-"];
        if (idArray.count == 3) {
            _pId = idArray[0];
            _cId = idArray[1];
            _aId = idArray[2];
            [[NSUserDefaults standardUserDefaults] setValue:_pId forKey:@"pId"];
            [[NSUserDefaults standardUserDefaults] setValue:_cId forKey:@"cId"];
            [[NSUserDefaults standardUserDefaults] setValue:_aId forKey:@"aId"];
        }
    }else if (indexPath.row == 2){ //场所
        _position = dic[@"id"];
        _position_name = dic[@"name"];
    }else if (indexPath.row == 3){//店铺来源
        _from_type = dic[@"id"];
    }else{//位置
        NSArray *zuobiaoArray = [dic[@"name"] componentsSeparatedByString:@","];
        if (zuobiaoArray.count == 2) {
            _latitude = zuobiaoArray[0];
            _longitude = zuobiaoArray[1];
        }
    }
//    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"place" object:nil];
}

#pragma mark - 点击事件

- (IBAction)backButtonClick:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark  - tableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *arrayIndex = _dataArray[indexPath.row][1];
    NSString *titles = _dataArray[indexPath.row][0];
    if ([arrayIndex isEqualToString:@"1"]) {
        AddShopTableViewCell1 * cell = [tableView dequeueReusableCellWithIdentifier:kCell1];
        cell.labelName.text = titles;
        return cell;
    }else if ([arrayIndex isEqualToString:@"2"]){
        AddShopTableViewCell2 * cell = [tableView dequeueReusableCellWithIdentifier:kCell2];
        cell.labelName.text = titles;
        cell.textFieldContent.tag = 500 + indexPath.row;
        if (_upDateArray.count > 0) {
            cell.textFieldContent.text = _upDateArray[indexPath.row];
        }
        if (indexPath.row == 5) {
            cell.textFieldContent.keyboardType = UIKeyboardTypeNumberPad;
        }else{
            cell.textFieldContent.keyboardType = UIKeyboardTypeDefault;
        }
        return cell;
    }else if ([arrayIndex isEqualToString:@"3"]){
        AddShopTableViewCell3 * cell = [tableView dequeueReusableCellWithIdentifier:kCell3];
        cell.labelName.text = titles;
        cell.buttonContent.tag = 500 + indexPath.row;

        if (indexPath.row == 6) {
            _pName = [[NSUserDefaults standardUserDefaults] valueForKey:@"pName"];
            _cName = [[NSUserDefaults standardUserDefaults] valueForKey:@"cName"];
            _aName = [[NSUserDefaults standardUserDefaults] valueForKey:@"aName"];
            
            _pId = [[NSUserDefaults standardUserDefaults] valueForKey:@"pId"];
            _cId = [[NSUserDefaults standardUserDefaults] valueForKey:@"cId"];
            _aId = [[NSUserDefaults standardUserDefaults] valueForKey:@"aId"];
            if (![BGFunctionHelper isNULLOfString:_pName]) {
                NSString *string = [NSString stringWithFormat:@"%@-%@-%@",_pName,_cName,_aName];
                [cell.buttonContent setTitle:string forState:UIControlStateNormal];
            }
        }
        
        if (_upDateArray.count > 0) {
            [cell.buttonContent setTitle:_upDateArray[indexPath.row] forState:UIControlStateNormal];
        }
        if ([@"地理位置" isEqualToString:titles]) {
            cell.imageViewRight.image = [UIImage imageNamed:@"dizhi"];
        }
        
        return cell;
    }else if ([arrayIndex isEqualToString:@"4"]){
        AddShopTableViewCell4 * cell = [tableView dequeueReusableCellWithIdentifier:kCell4];
        cell.textView.tag = 500 + indexPath.row;
        if (_upDateArray.count > 0) {
            cell.textView.text = _upDateArray[indexPath.row];
            cell.textView.placeholderStr = [BGFunctionHelper isNULLOfString:cell.textView.text] ? cell.textView.placeholderStr : @"";
            [cell.textView updateInfo];
        }
        return cell;
    }else if ([arrayIndex isEqualToString:@"5"]){
        AddShopTableViewCell5 * cell = [tableView dequeueReusableCellWithIdentifier:kCell5];
        cell.labelName.text = titles;
        cell.buttonChooseImage.tag = 500 + indexPath.row;
        if (_upDateArray.count > 0) {
            UIImageView *imageView = [[UIImageView alloc] init];
            _imageUrl = _model.img_url;
            [imageView sd_setImageWithURL:[NSURL URLWithString:_model.img_url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                [cell.buttonChooseImage setBackgroundImage:imageView.image forState:UIControlStateNormal];
            }];
        }
        return cell;
    }else{
        AddShopTableViewCell6 * cell = [tableView dequeueReusableCellWithIdentifier:kCell6];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *arrayIndex = _dataArray[indexPath.row][1];
    if ([arrayIndex isEqualToString:@"1"]) {
        return 40;
    }else if ([arrayIndex isEqualToString:@"2"]){
        return 50;
    }else if ([arrayIndex isEqualToString:@"3"]){
        return 50;
    }else if ([arrayIndex isEqualToString:@"4"]){
        return 150;
    }else if ([arrayIndex isEqualToString:@"5"]){
        return 150;
    }else{
        return 100;
    }
}

#pragma mark - 提交数据

- (void)uploadData{
    NSLog(@"增加");
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] newShopInfoByEid:kUserId name:_shopName contact:_merPerson tel:_merPsersonNum latitude:_latitude longitude:_longitude province_id:_pId city_id:_cId area_id:_aId specific_address:_shopPlaceDetail province_name:_pName city_name:_cName area_name:_aName position:_position position_name:_position_name img_url:_imageUrl from_type:_from_type remark:_remark progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"门店创建成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

- (void)updateData{
    NSLog(@"更新");
    [self.hub hideAnimated:YES];
    self.hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    // Set the label text.
    self.hub.label.text = NSLocalizedString(@"加载中...", @"HUD loading title");
    [[AFClient shareInstance] updateShopInfoByShopId:_model.id eid:kUserId name:_shopName contact:_merPerson tel:_merPsersonNum latitude:_latitude longitude:_longitude province_id:_pId city_id:_cId area_id:_aId specific_address:_shopPlaceDetail province_name:_pName city_name:_cName area_name:_aName position:_position position_name:_position_name img_url:_imageUrl from_type:_from_type remark:_remark progressBlock:nil success:^(id responseBody) {
        [self.hub hideAnimated:YES];
        if ([responseBody[@"code"] integerValue] == 200) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"门店信息更新成功" message:nil preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            kAlert(responseBody[@"message"]);
        }
    } failure:^(NSError *error) {
        [self.hub hideAnimated:YES];
    }];
}

#pragma mark - 初始化数组

- (NSArray *)dataArray{
    if (_dataArray) {
        return _dataArray;
    }
    _dataArray = @[@[@"普通信息",@"1"]
                   ,@[@"店铺",@"2"]
                   ,@[@"场所",@"3"]
                   ,@[@"店铺来源",@"3"]
                   ,@[@"联系人",@"2"]
                   ,@[@"联系号码",@"2"]
                   ,@[@"省市",@"3"]
                   ,@[@"地理位置",@"3"]
                   ,@[@"详细地址",@"2"]
                   ,@[@"备注可留空",@"4"]
                   ,@[@"店铺图片(1张)",@"5"]
                   ,@[@"",@"6"]];
    return _dataArray;
}

- (void)alertVCByTitle:(NSString *)title{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:title preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
